package com.jftone.bh.app.action;

import java.util.ArrayList;
import java.util.List;

import com.jftone.bh.app.config.SysConst;
import com.jftone.bh.app.model.SysMenu;
import com.jftone.bh.app.model.SysMenuFunc;
import com.jftone.bh.app.model.SysParam;
import com.jftone.bh.app.service.SysMenuService;
import com.jftone.bh.app.service.SysParamService;
import org.apache.log4j.Logger;
import org.jftone.annotation.Autowired;
import org.jftone.annotation.Controller;
import org.jftone.exception.ActionException;
import org.jftone.exception.ComponentException;
import org.jftone.util.DataMap;
import org.jftone.util.IData;
import org.jftone.util.StringUtil;

@Controller(mapping="/sysMenuAction")
public class SysMenuAction extends BaseAction {
	private Logger logger = Logger.getLogger(SysMenuAction.class);
	
	@Autowired
	private SysParamService sysParamService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	/**
	 * 菜单首页载入
	 * @throws ActionException
	 */
	public void index() throws ActionException{
		IData<String, Object> inData = new DataMap<String, Object>();
		inData.put("parentCode", SysConst.ROOT_CODE);
		try {
			List<SysMenu> list  = sysMenuService.querySysMenu(inData);
			//权限控制主要集中的query方法里面，所有需要代入页面在query方法里加载
			this.putRenderInfo("rightCode", getRightCode());
			this.putRenderInfo("rootMenus", list);
		} catch (Exception e) {
			throw new ActionException("查询菜单根节点数据错误"+e.getMessage(), e);
		}
		this.render("sys_menu_main.html");
	}
	
	/**
	 * 加载菜单子目录
	 * @throws ActionException
	 */
	public void load() throws ActionException{
		IData<String, Object> data = getData();
		String menuCode = data.getString("menuCode");
		IData<String, Object> inData = new DataMap<String, Object>();
		inData.put("parentCode", menuCode);
		try {
			List<SysMenu> list  = sysMenuService.querySysMenu(inData);
			this.send(list);
		} catch (Exception e) {
			throw new ActionException("查询菜单根节点数据错误"+e.getMessage(), e);
		}
	}
	
	/**
	 * 加载菜单列表
	 * @throws ActionException
	 */
	public void query() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		int menuNode = data.getInt("menuNode", SysConst.MENU_NODE);
		String parentMenu="系统模块";
		try {
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("parentCode", parentCode);
			List<SysMenu> list  = sysMenuService.querySysMenu(inData);
			if(!parentCode.equals(SysConst.ROOT_CODE)){
				inData.clear();
				inData.put("menuCode", parentCode);
				SysMenu menu  = sysMenuService.getSysMenu(inData);
				parentMenu=menu.getMenuName();
			}
			//设置功能按钮
			setMenuFuncDerictive();
			//设置隐藏传值参数
			this.putRenderInfo(SysConst.QUERY_PARAMS, putParam("parentCode", parentCode).putParam("menuNode", menuNode).getParam());
			
			this.putRenderInfo("parentMenu", parentMenu);
			this.putRenderInfo("menus", list);
		} catch (Exception e) {
			logger.error("查询菜单数据错误"+e.getMessage(), e);
			throw new ActionException("查询菜单数据错误"+e.getMessage(), e);
		}
		this.render("sys_menu.html");
	}
	
	public void add() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		int menuNode = data.getInt("menuNode", SysConst.MENU_NODE);
		SysMenu menu = new SysMenu();
		String moduleCode = parentCode;
		try {
			List<IData<String, Object>> pdList  = null;
			List<SysMenu> menuNodes  = new ArrayList<SysMenu>();
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("parentCode", SysConst.ROOT_CODE);
			List<SysMenu> list  = sysMenuService.querySysMenu(inData);
			//非节点菜单
			if(menuNode != SysConst.MENU_NODE){
				pdList  = new ArrayList<IData<String, Object>>();
				inData.clear();
				inData.put("dataType", SysConst.MENU_FUNC_BTN);
				List<SysParam> paramList  = sysParamService.querySysParam(inData);
				for(SysParam sp : paramList){
					IData<String, Object> pd = new DataMap<String, Object>();
					pd.put("name", sp.getDataName());
					pd.put("code", sp.getDataCode());
					pd.put("limitNum", 0);
					pd.put("flag", false);
					pd.put("type", SysConst.MFB_TYPE_URL);
					pd.put("param", "");
					pdList.add(pd);
				}
				//查询模型节点
				inData.clear();
				inData.put("MENU_CODE", parentCode);
				IData<String, Object> nodeMenu  = sysMenuService.getMenuByParentCode(parentCode);
				if(null != nodeMenu){
					moduleCode = nodeMenu.getString("PARENT_CODE");
					
					//加载菜单节点数据
					inData.clear();
					inData.put("parentCode", moduleCode);
					menuNodes  = sysMenuService.querySysMenu(inData);
				}
			}
			menu.setParentCode(parentCode);
			menu.setClosed((short)0);
			menu.setSeqSort(0);
			this.putRenderInfo("moduleCode", moduleCode);
			this.putRenderInfo("menu", menu);
			this.putRenderInfo("params", pdList);
			this.putRenderInfo("moduleList", list);
			this.putRenderInfo("nodeList", menuNodes);
			this.putRenderInfo("menuNode", menuNode);
		} catch (Exception e) {
			logger.error("新增菜单数据错误"+e.getMessage(), e);
			throw new ActionException("新增菜单数据错误"+e.getMessage(), e);
		}
		this.render("sys_menu_form.html");
	}
	
	public void edit() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		int menuNode = data.getInt("menuNode", SysConst.MENU_NODE);
		String dataId = data.getString("dataId", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		String moduleCode = parentCode;
		try {
			List<IData<String, Object>> pdList  = null;
			List<SysMenu> menuNodes  = new ArrayList<SysMenu>();
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("parentCode", SysConst.ROOT_CODE);
			List<SysMenu> list  = sysMenuService.querySysMenu(inData);
			
			inData.clear();
			inData.put("id", Integer.parseInt(dataId));
			SysMenu menu = sysMenuService.getSysMenu(inData);
			//非节点菜单
			if(menuNode != SysConst.MENU_NODE){
				inData.clear();
				inData.put("menuCode", menu.getMenuCode());
				List<SysMenuFunc> smfList  = sysMenuService.querySysMenuFunc(inData);
				IData<String, SysMenuFunc> smfMap = new DataMap<String, SysMenuFunc>();
				for(SysMenuFunc smf : smfList){
					smfMap.put(smf.getFuncCode(), smf);
				}
				pdList  = new ArrayList<IData<String, Object>>();
				inData.clear();
				inData.put("dataType", SysConst.MENU_FUNC_BTN);
				List<SysParam> paramList  = sysParamService.querySysParam(inData);
				String keyCode = null;
				SysMenuFunc tmpSmf = null;
				for(SysParam sp : paramList){
					keyCode = sp.getDataCode();
					IData<String, Object> pd = new DataMap<String, Object>();
					if(smfMap.containsKey(keyCode)){
						tmpSmf = smfMap.get(keyCode);
						pd.put("name", sp.getDataName());
						pd.put("code", keyCode);
						pd.put("flag", true);
						pd.put("limitNum", tmpSmf.getLimitNum());
						pd.put("type", tmpSmf.getFuncType());
						pd.put("param", tmpSmf.getParam());
					}else{
						pd.put("name", sp.getDataName());
						pd.put("code", keyCode);
						pd.put("flag", false);
						pd.put("limitNum", 0);
						pd.put("type", SysConst.MFB_TYPE_URL);
						pd.put("param", "");
					}
					pdList.add(pd);
				}
				//查询模型节点
				IData<String, Object> nodeMenu  = sysMenuService.getMenuByParentCode(parentCode);
				if(null != nodeMenu){
					moduleCode = nodeMenu.getString("PARENT_CODE");
					//加载菜单节点数据
					inData.clear();
					inData.put("parentCode", moduleCode);
					menuNodes  = sysMenuService.querySysMenu(inData);
				}
			}else{
				moduleCode = parentCode;
			}
			this.putRenderInfo("moduleCode", moduleCode);
			this.putRenderInfo("menu", menu);
			this.putRenderInfo("params", pdList);
			this.putRenderInfo("moduleList", list);
			this.putRenderInfo("nodeList", menuNodes);
			this.putRenderInfo("menuNode", menuNode);
		} catch (Exception e) {
			logger.error("编辑菜单数据错误"+e.getMessage(), e);
			throw new ActionException("编辑菜单数据错误"+e.getMessage(), e);
		}
		this.render("sys_menu_form.html");
	}
	
	public void delete() throws ActionException{
		IData<String, Object> data = getData();
		String parentCode = data.getString("parentCode", SysConst.ROOT_CODE);
		int menuNode = data.getInt("menuNode", SysConst.MENU_NODE);
		String dataId = data.getString("dataId", "");
		if(StringUtil.isBlank(dataId) || !StringUtil.isNumber(dataId)){
			this.alertMsg("参数传值错误");
			return;
		}
		try {
			int resultCode = sysMenuService.deleteMenu(Integer.parseInt(dataId));
			if(resultCode == 1){
				this.alertMsg("数据错误，请刷新后重试");
				return;
			}else if(resultCode == 2){
				this.alertMsg("菜单节点有子节点，不能删除");
				return;
			}else if(resultCode == 3){
				this.alertMsg("菜单编码有关联的角色");
				return;
			}
			this.showMsg("系统菜单节点信息删除成功", "?method=query&parentCode="+parentCode+"&menuNode="+menuNode);
		} catch (ComponentException e) {
			logger.error("删除菜单数据错误"+e.getMessage(), e);
			throw new ActionException("删除菜单数据错误"+e.getMessage(), e);
		}
	}
	
	public void save() throws ActionException{
		boolean updateFlag = false;
		IData<String, Object> data = getData();
		String menuId = data.getString("menuId");
		int menuNode = data.getInt("menuNode", SysConst.MENU_NODE);
		String menuCode = data.getString("menuCode");
		try {
			SysMenu menu = new SysMenu();
			if(!StringUtil.isBlank(menuId) && StringUtil.isNumber(menuId)){
				menu.setId(Integer.parseInt(menuId));
				updateFlag = true;
			}
			String parentCode = SysConst.ROOT_CODE;
			if(menuNode == SysConst.MENU_NODE){
				parentCode = data.getString("moduleType");
			}else{
				parentCode = data.getString("parentCode");
			}
			menu.setParentCode(parentCode);
			menu.setMenuName(data.getString("menuName"));
			menu.setMenuCode(menuCode);
			menu.setSeqSort(data.getInt("seqSort"));
			menu.setClosed(Short.parseShort(data.getString("closed")));
			menu.setMenuUrl(data.getString("menuUrl"));
			menu.setRemark(data.getString("remark"));
			
			List<SysMenuFunc> funcs  = new ArrayList<SysMenuFunc>();
			String[] funcCode = data.getArray("funcCode");
			short limitNum = 0;
			if(funcCode != null && funcCode.length > 0){
				for(String code : funcCode){
					SysMenuFunc smf = new SysMenuFunc();
					smf.setMenuCode(menuCode);
					smf.setFuncCode(code);
					smf.setFuncType(Short.parseShort(data.getString("funcType_"+code)));
					smf.setParam(data.getString("param_"+code));
					smf.setLimitNum(data.getShort("limitNum_"+code, limitNum));
					funcs.add(smf);
				}
			}
			if(sysMenuService.saveMenu(menuNode, menu, funcs)==1){
				this.alertMsg("菜单编码跟数据库中已知菜单编码重复");
				return;
			}
			this.showMsg("系统菜单节点信息"+(updateFlag? "保存" : "新增")+"成功", "?method=query&parentCode="+parentCode+"&menuNode="+menuNode);
		} catch (ComponentException e) {
			logger.error("保存系统菜单节点信息错误："+e.getMessage(), e);
			throw new ActionException("保存系统菜单节点信息错误", e);
		}
	}
}
